package main

import (
	"fmt"
	"github.com/keybase/go-ps"
	"github.com/shirou/gopsutil/v3/process"
	"time"
)

var lastProcesses map[int]ps.Process

func init() {
	lastProcesses = make(map[int]ps.Process, 0)
}

func main() {
	ticker := time.NewTicker(3 * time.Second)
	for {
		<-ticker.C
		np, dp := monitorProcess()
		getServiceName(np)
		fmt.Println("start：", np)
		fmt.Println("stop：", dp)
		fmt.Println()
	}

	//for _, p := range pss {
	//    process, _ := process.NewProcess(int32(p.Pid()))
	//    cl, _ := process.Cmdline() //.Cmdline()
	//    fmt.Println(process, cl)
	//    //path, _ := p.Path()
	//    if strings.Contains(strings.ToLower(cl), "java") {
	//
	//        fmt.Println(p)
	//    }
	//}
	//ps := goprocess.FindAll()
	//for _, v := range ps {
	//    fmt.Println(v)
	//}

}

func monitorProcess() ([]ps.Process, []ps.Process) {
	pss, err := ps.Processes()
	if err != nil {
		return nil, nil
	}

	nps := make([]ps.Process, 0)
	for _, p := range pss {
		if _, ok := lastProcesses[p.Pid()]; !ok {
			lastProcesses[p.Pid()] = p
			nps = append(nps, p)
		}
	}
	dps := make([]ps.Process, 0)
	for pid, p1 := range lastProcesses {
		isExists := false
		for _, p2 := range pss {
			if pid == p2.Pid() && p2.PPid() == p1.PPid() {
				isExists = true
				break
			}
		}
		if !isExists {
			delete(lastProcesses, p1.Pid())
			dps = append(dps, p1)
		}

	}
	return nps, dps
}

func getServiceName(nps []ps.Process) {
	for _, p1 := range nps {
		p, err := process.NewProcess(int32(p1.Pid()))
		if err != nil {
			fmt.Println(err)
			continue
		}
		fmt.Println(p1.Path())
		fmt.Println(p.Cmdline())
		fmt.Println(p.Connections())
	}

}

//
//func isJava() bool {
//    var results []Process
//
//    pss, err := ps.Processes()
//    if err != nil {
//        return false
//    }
//
//    var wg sync.WaitGroup
//    wg.Add(len(pss))
//
//    for _, pr := range pss {
//        pr := pr
//        go func() {
//            defer wg.Done()
//            pr.Path()
//            path, version, agent, ok, err := isGo(pr)
//            if err != nil {
//                // TODO(jbd): Return a list of errors.
//            }
//            if !ok {
//                return
//            }
//            results = append(results, P{
//                PID:          pr.Pid(),
//                PPID:         pr.PPid(),
//                Exec:         pr.Executable(),
//                Path:         path,
//                BuildVersion: version,
//                Agent:        agent,
//            })
//        }()
//    }
//    wg.Wait()
//    return results
//}
